local IndexController = {}
local db = require 'models.db'
local page = require 'library.pageobj'
local helper = require 'library.helpers'
local cache = require ('library.cache'):new()

function IndexController:_init_cache(action_name,controller_name)
    local get = self:getRequest():getParams()
    if action_name=='index' then
        local tag_id  = helper:intval(get['tag_id'])
        local page  = helper:intval(get['page'])
        local response= self:getResponse()

        if page<1 then
            page=1
        end

        response.cache_name="index/index/tag-"..tag_id.."-page-"..page
        response.cache_life=helper:intval(helper:config_get('index_cache'))
    end
end

function IndexController:index()
    local get = self:getRequest():getParams()
    local tag_id  = helper:intval(get['tag_id'])
    local p = {}
    local page_params = {}
    local article_db=db:new('article','art') 
    local response= self:getResponse()

    article_db:keep(true)

    if tag_id and tag_id~=0 then
        article_db:leftjoin("articles_tags tag","tag.aid=art.id"):where("tag.tid=?",tag_id)
        page_params["tag_id"]=tag_id
        p['tag_id']=tag_id
    else
        tag_id=0
    end
    
    page_params["page"]=":page:"

    local pageobj = page:new(article_db:count(),12,tonumber(get['page']),helper:url('index',page_params));
    local res = article_db:order('id desc'):limit(pageobj:limit()):get_list()

    article_db:clear()

    p['page'] = pageobj;
    p['articles'] = res;

    response.cache_name="index/index/tag-"..tag_id.."-page-"..pageobj.current_page

    return  self:display(p)
end

--本来这里应该是全文index,不过有点麻烦,以后再研究修改
function IndexController:search()
    local get = self:getRequest():getParams()
    local p = {}
    local page_params = {}
    local article_db=db:new('article','art') 
    local word=get['word']

    if word then
        article_db:where("art.title like '%%?%%' or art.content like '%%?%%'",word,word,false)
        page_params["word"]=word
        p['word']=word
    else
        tag_id=0
    end

    article_db:keep(true)

    page_params["page"]=":page:"

    local pageobj = page:new(article_db:count(),12,tonumber(get['page']),helper:url('index/search',page_params));
    local res = article_db:order('id desc'):limit(pageobj:limit()):get_list()

    article_db:clear()

    p['page'] = pageobj;
    p['articles'] = res;

    return  self:display('index/index.html',p)
end

return IndexController
